package com.example.docking.util;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class OrderNumberGenerator {
    // 单号前缀
    private static final String BASE_NUMBER = "W";
    // 日期格式
    private static final String DATE_FORMAT = "yyyy";
    // 文件扩展名
    private static final String FILE_EXTENSION = ".txt";

    /**
     * 生成订单号
     *
     * @return 生成的订单号
     */
    public String generateOrderNumber() {
        LocalDate currentDate = LocalDate.now();
        // 格式化当前日期作为文件名的一部分
        String datePart = currentDate.format(DateTimeFormatter.ofPattern(DATE_FORMAT));
        String folderName = "orderNum";
        File folder = new File(folderName);
        if (!folder.exists()) {
            boolean success = folder.mkdir();
            if (!success) {
                throw new RuntimeException("Failed to create folder: " + folderName);
            }
        }
        String filePath = folderName + "/" + datePart + FILE_EXTENSION;
        int numberPart = 1;

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            // 尝试读取文件内容
            String line = reader.readLine();
            if (line != null) {
                // 如果读取到内容，解析出单号的数字部分并加一
                //String[] parts = line.split("");
                numberPart = Integer.parseInt(line.substring(line.length() - 4)) + 1;
            }
        } catch (IOException e) {
            // 文件不存在或者读取失败，将数字部分初始化为 1
            // 这种情况下后续会创建新文件并写入初始单号
        }

        // 将数字部分格式化为 5 位，不足的前面补 0
        String newNumberPart = String.format("%04d", numberPart);
        // 生成新的订单号
        String newOrderNumber = BASE_NUMBER + datePart + newNumberPart;

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            // 将新的订单号写入文件
            writer.write(newOrderNumber);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newOrderNumber;
    }

    public static void main(String[] args) {
        OrderNumberGenerator generator = new OrderNumberGenerator();
        String orderNumber = generator.generateOrderNumber();
        System.out.println("Generated Order Number: " + orderNumber);
    }

}